﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace 日志的使用.自定义的内容
{
    /// <summary>
    /// 异常过滤器
    /// </summary>
    public class SelfExceptionFilter : IAsyncExceptionFilter
    {
        private readonly IHostEnvironment hostEnv;
        private readonly ILogger<SelfExceptionFilter> log;
        public SelfExceptionFilter(IHostEnvironment hostEnv, ILogger<SelfExceptionFilter> log)
        {
            this.hostEnv = hostEnv;
            this.log = log;
        }


        public Task OnExceptionAsync(ExceptionContext context)
        {
            String msg = hostEnv.IsDevelopment() ?context.Exception.ToString() : "服务器出现异常信息";
            log.LogError("异常", context.Exception);

            ObjectResult objectResult = new ObjectResult(new { code = 500, Mes = msg });
            context.Result = objectResult;  //Result中的值会被输出到客户端
            context.ExceptionHandled = true; //表示该异常已经被处理，其它异常的Filter就不会被执行
            return Task.CompletedTask;
        }
    }
}
